<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="dataForm.courseName"
          placeholder="课程名称"
        ></el-input>
      </el-form-item>




        <el-form-item label="课程封面" prop="courseHover" >
          <div class="avatar-container">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8888/api/minio/upload"
              :show-file-list="false"
              :on-preview="handlePictureCardPreview"
              :on-success="handleUploadSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img style="width: 150px;height: 150px" v-if="dataForm.courseHover" :src="dataForm.courseHover" class="avatar" alt="">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
      </el-form-item>


      <el-form-item label="课程价格" prop="coursePrice">
        <el-input
          v-model="dataForm.coursePrice"
          placeholder="课程价格"
        ></el-input>
      </el-form-item>

      <el-form-item label="课程点赞" prop="likeNumber">
        <el-input
          v-model="dataForm.likeNumber"
          placeholder="课程点赞"
        ></el-input>
      </el-form-item>

      <el-form-item label="课程收藏" prop="collectNumber">
        <el-input
          v-model="dataForm.collectNumber"
          placeholder="课程收藏"
        ></el-input>
      </el-form-item>



      <el-form-item label="课程简介(不超过100个字)" prop="courseDescription">
        <el-input
          v-model="dataForm.courseDescription"
          placeholder="课程简介(不超过100个字)"
        ></el-input>
      </el-form-item>


      <el-form-item label="课程类型" prop="courseTypeName">
        <el-select v-model="dataForm.courseTypeName" placeholder="请选择">
          <el-option
            v-for="item in courseTypeOption"
            :key="item.id"
            :label="item.courseTypeName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程讲师" prop="teacherName">
        <el-select v-model="dataForm.teacherName" placeholder="请选择">
          <el-option
            v-for="item in teacherOption"
            :key="item.id"
            :label="item.teacherName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        id: 0,
        courseName: '',
        courseHover: '',
        courseDescription: '',
        courseTypeName: '',
        teacherName: '',
        createTime: '',
        coursePrice: '',
        likeNumber: '',
        collectNumber: '',
        updateTime: '',
        isDelete: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [
        {
          name: '',
          url: ''
        }
      ],
      flag: true,
      imageUrl: '',
      courseTypeOption: [],
      teacherOption: [],
      dataRule: {
        courseName: [
          { required: true, message: '课程名字不能为空', trigger: 'blur' }
        ],
        courseHover: [
          { required: true, message: '课程封面不能为空', trigger: 'blur' }
        ],
        courseDescription: [
          {
            required: true,
            message: '课程简介(不超过100个字)不能为空',
            trigger: 'blur'
          }
        ],
        courseTypeName: [
          { required: true, message: '课程类型不能为空', trigger: 'blur' }
        ],
        teacherName: [
          { required: true, message: '课程讲师不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: false, message: '创建时间不能为空', trigger: 'blur' }
        ],
        updateTime: [
          { required: false, message: '修改时间不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    init (id) {
      this.getCoureseTypeList()
      this.getTeacherList()
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/course/course/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.courseName = data.course.courseName;
              this.dataForm.courseHover = data.course.courseHover;
              this.dataForm.courseDescription = data.course.courseDescription;
              this.dataForm.courseTypeName = data.course.courseTypeName;
              this.dataForm.teacherName = data.course.teacherName;
              this.dataForm.coursePrice = data.course.coursePrice;
              this.dataForm.likeNumber = data.course.likeNumber;
              this.dataForm.collectNumber = data.course.collectNumber;
              this.dataForm.createTime = data.course.createTime;
              this.dataForm.updateTime = data.course.updateTime;
              this.dataForm.isDelete = data.course.isDelete;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        this.setCoureseTypeId()
        this.setTeacherlId()
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/course/course/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              courseName: this.dataForm.courseName,
              courseHover: this.dataForm.courseHover,
              courseDescription: this.dataForm.courseDescription,
              courseTypeName: this.dataForm.courseTypeName,
              teacherName: this.dataForm.teacherName,
              coursePrice: this.dataForm.coursePrice,
              likeNumber: this.dataForm.likeNumber,
              collectNumber: this.dataForm.collectNumber,
              createTime: this.dataForm.createTime,
              updateTime: this.dataForm.updateTime,
              isDelete: this.dataForm.isDelete
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit('refreshDataList');
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 获取课程类型列表
    getCoureseTypeList () {
      this.$http({
        url: this.$http.adornUrl(
          '/course/coursetype/findCourseTypeList'
        ),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data.courseTypeList);
          this.courseTypeOption = data.courseTypeList;
        } else {
          this.courseTypeOption = [];
        }
      });
    },
    // 获取讲师下拉框
    getTeacherList () {
      this.$http({
        url: this.$http.adornUrl(
          '/teacher/teacher/findTeacherList'
        ),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data.teacherList);
          this.teacherOption = data.teacherList;
        } else {
          this.teacherOption = [];
        }
      });
    },

    // 打开编辑框的时候为等级和类型设置对应的id
    setCoureseTypeId () {
      if (typeof this.dataForm.courseTypeName === 'string') {
        for (var i = 0; i < this.courseTypeOption.length; i++) {
          if (
            this.dataForm.id &&
            this.dataForm.courseTypeName === this.courseTypeOption[i].courseTypeName
          ) {
            this.dataForm.courseTypeName = this.courseTypeOption[i].id;
          }
          console.log(this.dataForm.courseTypeName, 'sadas');
        }
      }
    },

    setTeacherlId () {
      if (typeof this.dataForm.teacherName === 'string') {
        for (var i = 0; i < this.teacherOption.length; i++) {
          if (
            this.dataForm.id &&
            this.dataForm.teacherName === this.teacherOption[i].teacherName
          ) {
            this.dataForm.teacherName = this.teacherOption[i].id;
          }
          console.log(this.dataForm.teacherName, 'sadas');
        }
      }
    },
    handlePreview (file) {
      console.log(file);
    },

    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview (file) {
      console.log(file);
      this.dataForm.courseHover = file.url;
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleUploadSuccess (res, file) {
      console.log(res, 'res')
      console.log(file, 'file')
      this.dataForm.courseHover = res.msg

      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload (file) {
      console.log(file.type, 'file')
      const isJPG = file.type === 'image/jpeg';
      const isPng = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPng) {
        this.$message.error('上传头像图片只能是 JPG或PNG格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return (isJPG || isPng) && isLt2M;
    },
    updateFlag () {
      if (this.dataForm.courseHover !== '') {
        this.flag = true;
      } else {
        this.flag = false;
      }
      console.log(this.flag);
    },
    close () {
      this.visible = false;
      this.handleRemove(this.fileList);
    }
  }
};
</script>
<style>
.avatar-container {
  display: flex;
}

</style>
